package com.dev.weixin.platform.controllers;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.dev.weixin.platform.beans.WXConfig;
import com.dev.weixin.platform.service.IWXConfigService;
import com.dev.weixin.tools.models.receive.ValidData;
import com.dev.weixin.tools.service.ReceiveService;

/**
 * @author 飘渺青衣
 * @see
 */
@Controller
@RequestMapping("/weixin/{userId}/listener")
public class ListenerController {
	
	private static final Logger LOG = LogManager.getLogger(ListenerController.class);

	@Autowired
	private ReceiveService receiveService;
	
	@Autowired
	private IWXConfigService wxConfigService;
	
	@RequestMapping(method = RequestMethod.GET)
	public @ResponseBody String get(@PathVariable("userId") String userId, ValidData valid) {
		try {
			String toUserName = "";
			WXConfig config = this.wxConfigService.findWXConfig(userId);
			if(config != null) {
				toUserName = config.getOriginalId();
			}
			if(StringUtils.isNotEmpty(toUserName) && 
					this.receiveService.checkSignature(toUserName, valid)) {
				return valid.getEchostr();
			}
		} catch(Exception e) {
			LOG.error("接入出错！", e);
		}
		return "";
	}
	
	@RequestMapping(method = RequestMethod.POST)
	public @ResponseBody String post(
			HttpServletRequest request,
			@PathVariable("userId") String userId, 
			ValidData valid) {
		try {
			return this.receiveService.receive(valid, request.getInputStream());
		} catch(Exception e) {
			LOG.error("接收信息出错！", e);
		}
		return "";
	}
	
}
